package com.efounder.interfaces;

import android.content.Context;

import com.core.xml.StubObject;
import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.ChatListItem;
import com.efounder.chat.model.RefreshChatItemEvent;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.chat.service.SystemInfoService;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.service.Registry;
import com.efounder.util.EnvSupportManager;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * Created by lch on 2017/6/5.
 */

public class BadgeUtil {
    public static final int CHAT_ID_MESSAGE = -1;//消息的id
    public static final int CHAT_ID_CONTACTS = -2;//通讯录的id
    public static final int CHAT_ID_TASK = -3;//任务的id
    public static final int CHAT_ID_ZONE = -4;//空间引力场的id

    public static final int CHAT_ID_TASK_DB = -5;//石油任务待办的id
    public static final int CHAT_ID_TASK_YB = -6;//石油任务已办的id
    public static int CHAT_ID_TASK_DB_COUNT = 0;//石油任务待办的数量

    public static final int CHAT_ID_NEWS = -8;//新闻资讯


    public static Map<String, List> badgeMap = new HashMap<>();
    //所有的应用号角标 //TODO 这个list应该存放的int ，但是开始写代码的时候搞成String了 使用contains方法的时候需要注意 ,后来发现放string还是比较不错的，因为int类型太短了
    public static List appIDs = new ArrayList();
    private static final String KEY_MENU_ROOT = "menuRoot";

    public static int getTotalUnReadNum() {
        return totalUnReadNum;
    }

    public static void setTotalUnReadNum(int totalUnReadNum) {
        BadgeUtil.totalUnReadNum = totalUnReadNum;
    }

    public static int totalUnReadNum = -1;


    //初始化角标
    public static void initBadge() {
        BadgeUtil.badgeMap.clear();
        appIDs.clear();
        Map<String, StubObject> map = Registry.registryNodeStore;
        for (String key : map.keySet()) {
            initBadgeONLayer(key);
        }
    }

    //遍历资源文件树
    private static void treeNode(StubObject stubObject, List list) {
        String xmlAppId = stubObject.getObject("appId", "").toString();
        String id = stubObject.getString("id", "");

        if (!xmlAppId.equals("")) {
            list.add(xmlAppId);
            appIDs.add(xmlAppId);
            List<String> listXml = new ArrayList<>();
            listXml.add(xmlAppId);
            badgeMap.put(id, listXml);
        }
        String type = stubObject.getString("viewType", "");
        String permission = stubObject.getString("permission", "");
        String gnqxString = EnvironmentVariable.getProperty("gnqx", "");
        String studID = stubObject.getString("id", "");

        //判断是否拥有权限
        if (gnqxString != null) {
            if (!"".equals(permission) && permission != null) {
                String[] gnqxStrings = gnqxString.split(";");
                for (int j = 0; j < gnqxStrings.length; j++) {
                    String gnqx = gnqxStrings[j];
                    if (gnqx.equals(permission)) {
                        break;
                    } else {
                        if (j == gnqxStrings.length - 1) {
                            return;
                        }
                    }
                }
            }
        }

        //如果是消息列表的话，添加一个-1
        if (type.equals("message") || "message".equals(studID)) {
            list.add(CHAT_ID_MESSAGE + "");
            List<String> messageList = new ArrayList<>();
            messageList.add(CHAT_ID_MESSAGE + "");
            badgeMap.put(type, messageList);

        } else if (type.equals("txl")) {//通讯录 -2
            list.add(CHAT_ID_CONTACTS + "");
            List<String> txlList = new ArrayList<>();
            txlList.add(CHAT_ID_CONTACTS + "");
            badgeMap.put(type, txlList);
        } else if (type.equals("flowTask")) {//任务 -3
            list.add(CHAT_ID_TASK + "");
            List<String> txlList = new ArrayList<>();
            txlList.add(CHAT_ID_TASK + "");
            badgeMap.put(id, txlList);
        }
        //这里往下根据stubID 判断
        //<node id="task_db" caption="待办"  viewType="display" AndroidShow="com.efounder.task.CwgxTaskFragment" showBadge="true" />

        else if (studID.equals("daiban")) {//任务 -3
            list.add(CHAT_ID_TASK + "");
            List<String> txlList = new ArrayList<>();
            txlList.add(CHAT_ID_TASK + "");
            badgeMap.put(id, txlList);
        } else if (studID.equals("tansuo")) {//星际通讯空间探索
            list.add(CHAT_ID_ZONE + "");
            List<String> txlList = new ArrayList<>();
            txlList.add(CHAT_ID_ZONE + "");
            badgeMap.put(id, txlList);
        } else if (studID.equals("task_db")) {//任务待办 yqs
            list.add(CHAT_ID_TASK_DB + "");
            List<String> txlList = new ArrayList<>();
            txlList.add(CHAT_ID_TASK_DB + "");
            badgeMap.put(id, txlList);
        } else if (studID.equals("task_yb")) {//任务已办 yqs
            list.add(CHAT_ID_TASK_YB + "");
            List<String> txlList = new ArrayList<>();
            txlList.add(CHAT_ID_TASK_YB + "");
            badgeMap.put(id, txlList);
            //MuleDelivery的“我的”界面md_wd
        } else if (studID.equals("md_wd")) {
            list.add(CHAT_ID_MESSAGE + "");
            List<String> txlList = new ArrayList<>();
            txlList.add(CHAT_ID_MESSAGE + "");
            badgeMap.put(id, txlList);
        }
//        else if (studID.equals("sy_task")) {//任务石油 yqs
//            list.add(CHAT_ID_TASK_SY + "");
//            List<String> txlList = new ArrayList<>();
//            txlList.add(CHAT_ID_TASK_SY + "");
//            badgeMap.put(id, txlList);
//        }
        //资产首页有消息入口
        else if (EnvSupportManager.isAssetHasMsg() && studID.equals("total_assets")) {
            list.add(CHAT_ID_MESSAGE + "");
            List<String> txlList = new ArrayList<>();
            txlList.add(CHAT_ID_MESSAGE + "");
            badgeMap.put(id, txlList);
        }
        else if (studID.equals("zixun")) {//新闻资讯
            list.add(CHAT_ID_NEWS + "");
            List<String> txlList = new ArrayList<>();
            txlList.add(CHAT_ID_NEWS + "");
            badgeMap.put(id, txlList);
        }
        List<StubObject> childMenus = Registry.getRegEntryList((String) stubObject.getID());
        if (childMenus == null || childMenus.size() <= 0) {
            return;
        }

        //如果是可手工配置的则需要匹配本地的文件
        if (type.equals("home")) {
            homeTypeControl(stubObject, childMenus, list);
            return;
        }
        for (int i = 0; i < childMenus.size(); i++) {
            StubObject stubObject1 = childMenus.get(i);
            treeNode(stubObject1, list);
        }

    }

    //应用模块单独处理
    private static void initBadgeONLayer(String nodeID) {
        StubObject parentStubObject = Registry.getRegEntry(nodeID);
        List chatIDs = new ArrayList();

        List<StubObject> mainMenus = Registry.getRegEntryList(nodeID);
        if (mainMenus == null || mainMenus.size() <= 0) {
            return;
        }

        String type = parentStubObject.getString("viewType", "");


        if (type.equals("home")) {
            homeTypeControl(parentStubObject, mainMenus, chatIDs);
            badgeMap.put(nodeID, chatIDs);
            return;
        }

        for (int i = 0; i < mainMenus.size(); i++) {
            StubObject stubObject = mainMenus.get(i);
            treeNode(stubObject, chatIDs);
        }
        badgeMap.put(nodeID, chatIDs);
    }

    /**
     * handle app contact that shows red dot as a badge
     *
     * @param context context
     */
    public static List<String> handleAppContact(Context context) {
        String[] apps = context.getResources().getStringArray(R.array.red_dot_app_list);
        List<String> redDotBadgeAppIDs = new ArrayList();
        redDotBadgeAppIDs.addAll(Arrays.asList(apps));
        return redDotBadgeAppIDs;
    }

    private static void homeTypeControl(StubObject stubObject, List<StubObject> childMenus, List list) {
        //如果是可手工配置的则需要匹配本地的文件
        String titleStr = stubObject.getString("caption", "");
        // ArrayList<Object> stubObjectList = FilesOperationDataUtil.readFile(AppContext.getInstance(), titleStr);
        String userName = EnvironmentVariable.getUserName();
        String localString = EnvironmentVariable.getProperty(userName + "/" + titleStr, "");
        Map<String, String> localMap = new HashMap();
        if (!localString.equals("")) {
            java.util.StringTokenizer items;
            for (StringTokenizer entrys = new StringTokenizer(localString, "^"); entrys.hasMoreTokens();
                 localMap.put(items.nextToken(), items.hasMoreTokens() ? ((String) (items.nextToken())) : null)) {
                items = new StringTokenizer(entrys.nextToken(), "'");
            }
        }
        for (int k = 0; k < childMenus.size(); k++) {
            StubObject xmlStubObject = childMenus.get(k);
            String childXMLAppId = xmlStubObject.getObject("appId", "").toString();
            String childXMLId = xmlStubObject.getObject("id", "").toString();
            String isShowBadge = xmlStubObject.getObject("isShowBadge", "").toString();
            //if(!isShowBadge.equals("")){continue;}
            if (childXMLAppId.equals("")) {
                continue;
            }
            String xmlid = xmlStubObject.getString("id", "");
            if (localMap.containsKey(xmlid)) {
                String value = localMap.get(xmlid);
                if (value.equals("1")) {
                    if (isShowBadge.equals("") || isShowBadge.equals("true")) {
                        list.add(childXMLAppId);
                    }
                    appIDs.add(childXMLAppId);
                }
            } else {
                if (isShowBadge.equals("") || isShowBadge.equals("true")) {
                    list.add(childXMLAppId);
                }
                appIDs.add(childXMLAppId);
            }
        }

    }

    public static int getCount(String id) {
        int count = 0;

        List chatIDs = badgeMap.get(id);
        if (chatIDs == null || chatIDs.size() <= 0) {
            return 0;
        }
        for (int i = 0; i < chatIDs.size(); i++) {
            int chatID = Integer.parseInt(chatIDs.get(i) + "");
            if (chatID > 0) {
                int unreadCount = JFMessageManager.getInstance().getUnReadCount(chatID, (byte) 0);
                count += unreadCount;
            } else if (chatID == CHAT_ID_MESSAGE) {//消息列表
                count += getChatListUnReadCount();

            } else if (chatID == CHAT_ID_CONTACTS) {//通讯录
                //TODO 同上
                count += getPhoneBookUnReadCount();
            } else if (chatID == CHAT_ID_TASK) {//任务
                String flowUnreadCountPending = EnvironmentVariable.getProperty("Badge_Task_Pending", "0");

                String flowUnreadCountProcessed = EnvironmentVariable.getProperty("Badge_Task_Processed", "0");
                count += Integer.parseInt(flowUnreadCountPending) + Integer.parseInt(flowUnreadCountProcessed);
            } else if (chatID == CHAT_ID_TASK_DB) {//任务待办 yqs
//                String flowUnreadCountPending = EnvironmentVariable.getProperty("Badge_Task_Pending", "0");
//                count += Integer.parseInt(flowUnreadCountPending);
                count += CHAT_ID_TASK_DB_COUNT;
            }
//            else if (chatID == CHAT_ID_TASK_YB) {//任务已办 yqs
//                String flowUnreadCountProcessed = EnvironmentVariable.getProperty("Badge_Task_Processed", "0");
//                if (count == 0) {
//                    count = Integer.parseInt(flowUnreadCountProcessed);
//                    return count;
//                } else {
//                    return count;
//                }
//            }
//            else if (chatID == CHAT_ID_TASK_SY) {//石油返回待办数量 yqs
//                String flowUnreadCountPending = EnvironmentVariable.getProperty("Badge_Task_Pending", "0");
//                count= Integer.parseInt(flowUnreadCountPending);
//            }

            else if (chatID == CHAT_ID_NEWS) {//新闻资讯的角标
//                if (count != 0) {
//                    return count;
//                }
                if (!"zixun".equals(id)) {
                    return count;
                } else {
                    if (EnvironmentVariable.getProperty("news_new_message_notify", "0").equals("1")) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
//                count += 0;
            } else if (chatID == CHAT_ID_ZONE) {//引力场空间
                //解析 当count 大于0时，我们忽略空间的角标，因为空间下面最多只会显示红点，<=0 表示其他业务系统暂无角标，就可以显示空间的角标了
                String hasNewMessage = EnvironmentVariable.getProperty("zone_has_new_message");
                String hasNewPost = EnvironmentVariable.getProperty("zone_has_new_post");
                if (hasNewMessage != null && !hasNewMessage.equals("") && !hasNewMessage.equals("true")
                        && !hasNewMessage.equals("false") && !hasNewMessage.equals("0")) {
                    // count = -1;
                    if (count <= 0) {
                        count = -1;
                    }

                } else if (hasNewPost != null && hasNewPost.equals("true")) {
                    //count = -1;
                    if (count <= 0) {
                        count = -1;
                    }
                } else {
                    if (count <= 0) {
                        count = 0;
                    }
                }
            }

        }
        return count;
    }

    /**
     * 清除角标
     *
     * @param id nodeId 如"xiaoxi"等
     */
    public static void clearBadge(String id) {
        List chatIDs = badgeMap.get(id);
        if (chatIDs == null || chatIDs.size() <= 0) {
            return;
        }
        for (int i = 0; i < chatIDs.size(); i++) {
            int chatID = Integer.parseInt(chatIDs.get(i) + "");
            if (chatID > 0) {
                // FIXME: 18-8-29 unreadZero 是未读置为0吗？
                JFMessageManager.getInstance().unreadZero(chatID, (byte) 0);
            } else if (chatID == CHAT_ID_MESSAGE) {
                //清除消息列表角标
                clearChatListUnReadCount();
                //刷新角标
                UpdateBadgeViewEvent updateBadgeViewEvent = new UpdateBadgeViewEvent(BadgeUtil.CHAT_ID_MESSAGE + "", (byte) 0);
                EventBus.getDefault().post(updateBadgeViewEvent);
            } else if (chatID == CHAT_ID_CONTACTS) {
                //清空通讯录角标
                clearPhoneBookBadge();
                EventBus.getDefault().post(new UpdateBadgeViewEvent(CHAT_ID_CONTACTS + "", (byte) 0));

            } else if (chatID == CHAT_ID_TASK) {
                //清空任务角标
                EnvironmentVariable.setProperty("Badge_Task_Pending", "0");
                EnvironmentVariable.setProperty("Badge_Task_Processed", "0");
                EventBus.getDefault().post(new UpdateBadgeViewEvent("-3", (byte) 0));

            } else if (chatID == CHAT_ID_ZONE) {
                //清空空间角标
                EnvironmentVariable.setProperty("zone_has_new_message", "0");
                EnvironmentVariable.setProperty("zone_has_new_post", "0");
                EventBus.getDefault().post(new UpdateBadgeViewEvent(CHAT_ID_ZONE + "", (byte) 0));

            }
        }
    }

    /**
     * 消息里页所在的tab角标控制
     */
    private static int getChatListUnReadCount() {

        //处理消息页-------------
        int countNum = 0;
        List<ChatListItem> chatListItems = SystemInfoService.CHATITEMLIST;
        if (null != chatListItems && chatListItems.size() > 0) {
            for (ChatListItem item : chatListItems) {
                String chatID = item.getUserId() + "";

                boolean isnotReachAble = false;
                if (appIDs.contains(chatID))//说明应用模块配置了角标，所以列表里就变成了红点。设置成不用获取角标
                {
                    isnotReachAble = true;
                }

                if (isnotReachAble) {
                    item.setBadgernum(-1);
                    continue;
                } else {
//                    int chatType = item.getChatType();
//                    if (item.getChatType() == StructFactory.TO_USER_TYPE_PERSONAL
//                            || item.getChatType() == StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT) {
//                        item.setBadgernum(JFMessageManager.getInstance().getUnReadCount(Integer.parseInt(chatID), (byte) 0));
//                    } else {
//                        item.setBadgernum(JFMessageManager.getInstance().getUnReadCount(Integer.parseInt(chatID), (byte) item.getChatType()));
//                    }
                }

                if (item.getBadgernum() != -1) {
                    countNum += item.getBadgernum();
                }

            }

        }
        return countNum;
        //处理消息页-------------结束


    }

    /**
     * 清除消息里页所在的tab角标
     */
    private static void clearChatListUnReadCount() {
        List<ChatListItem> chatListItems = SystemInfoService.CHATITEMLIST;
        if (null != chatListItems && chatListItems.size() > 0) {
            for (ChatListItem item : chatListItems) {
                int chatID = item.getUserId();
                byte chatType = (byte) item.getChatType();
//                ChatListManager chatListManager = new ChatListManager();
//                chatListManager.clearunReadCount(weChatDBManager, chatID, chatType);
                item.setBadgernum(-1);
                JFMessageManager.getInstance().unreadZero(chatID, chatType);
            }
        }
        //通知聊天item 角标刷新
        EventBus.getDefault().post(new RefreshChatItemEvent(0));
    }


    /**
     * 通讯录页所在的tab角标控制
     */
    private static int getPhoneBookUnReadCount() {

        //处理通讯录
        int newFriendCount = WeChatDBManager.getInstance().getNewFriendUnread();
        int groupNoticeCount = WeChatDBManager.getInstance().getGroupNoticveUnreadCount();
        return newFriendCount + groupNoticeCount;

    }

    /**
     * 清空通讯录角标
     **/
    private static void clearPhoneBookBadge() {
        WeChatDBManager.getInstance().updateAllNewFriendsSetIsRead();
        WeChatDBManager.getInstance().setAllGroupNoticeIsRead();
    }

    //判断是否需要刷新角标
    public static boolean isNeedRefreshBadge(List list, int chatID, byte chatType) {
        boolean isNeedRefreshBadge = false;
        if (null == list) {
            return false;
        }
        //如果是群聊
        if (chatType == (byte) 1) {
            if (list.contains(CHAT_ID_MESSAGE + "")) {
                return true;
            }
        }

        if (list.contains(chatID + "")) {
            isNeedRefreshBadge = true;
        } else {
            if (list.contains(CHAT_ID_MESSAGE + "")) {
                if (!appIDs.contains(chatID)) {
                    isNeedRefreshBadge = true;
                }
            }

        }
        return isNeedRefreshBadge;
    }

    public static void refresh(List list, int chatID, byte chatType) {
        if (null == list) {
            return;
        }
        //如果是群聊
        if (chatType == (byte) 1) {
            if (list.contains(-1 + "")) {

            }
        }
    }

    //得到角标总数
    public static int initTotal() {

        try {
            List<StubObject> mainMenus = Registry.getRegEntryList(KEY_MENU_ROOT);
            int num = 0;
            for (int i = 0; i < mainMenus.size(); i++) {
                StubObject stubObject = mainMenus.get(i);
                String id = (String) stubObject.getID();

                List chatIDs = BadgeUtil.badgeMap.get(id);
                int unReadCount = BadgeUtil.getCount(id);

                num += unReadCount;
            }
            totalUnReadNum = num;
            return num;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

}
